<template>
    <div class="login-container h-full w-full flex flex-center">
        <div class="flex flex-col w-50% self-stretch image">
            <p>Welcome!</p>
            <h1>欢迎您来到{{ title }}</h1>
            <div class="flex flex-1 flex-center">
                <img src="@/assets/images/login-left-icon.png" alt="">
            </div>
        </div>
        <div class="w-50% self-stretch flex-center form">
            <div class="w-350px">
                <div class="text-center">
                    <h2 class="flex flex-center font-bold">欢迎登录</h2>
                </div>
                <el-form ref="loginFormRef" :model="LogParams" :rules="loginRules" class="login-form">
                    <div class="input-item">
                        <el-form-item prop="username">
                            <el-input v-model="LogParams.username" class="flex-1" name="username"></el-input>
                        </el-form-item>
                        
                    </div>
                    <div class="input-item relative">
                        <el-tooltip :disabled="isCapslock === false" content="大写按键已开启" placement="right">
                            <el-form-item prop="password">
                                <el-input v-model="LogParams.protoPassword" class="flex-1" :type="passwordVisible === false ? 'password' : 'input'" name="protoPassword" @keyup="checkCapslock" @keyup.enter="handleLogin" />
                                <span class="absolute" @click="passwordVisible = !passwordVisible">
                                    <svg-icon size="16px" :icon-class="passwordVisible === false ? 'eye-off-fill' : 'eye-fill'" class="cursor-pointer" />
                                </span>
                            </el-form-item>
                        </el-tooltip>
                    </div>
                    <div class="input-item">
                        <SlideVerify @success="onVerifySuccess" @failed="onVerifyFailed" />
                    </div>
                    
                    <el-button :loading="loading" :disabled="disabled" type="primary" size="large" class="w-full mt-30px h-40px" @click.prevent="handleLogin">登录</el-button>
                    <div class="flex flex-center mt-26px text-12px lh-16px">
                        访问本系统，建议使用谷歌(chrome)、火狐(firefox)浏览器访问
                    </div>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import router from '@/router';
import { useSettingsStore } from '@/store/modules/settings';
import SlideVerify from '@/components/SlideVerify/index.vue';

// 状态管理依赖
import { useUserStore } from '@/store/modules/user';
import { useAppStore } from '@/store/modules/app';

// API依赖
import { LocationQuery, LocationQueryValue, useRoute } from 'vue-router';
import { LoginParams } from '@/api/auth/types';

import CryptoJS from 'crypto-js';
 
const settingsStore = useSettingsStore();

const { title } = settingsStore;

const appStore = useAppStore();
const route = useRoute();
const userStore = useUserStore();

const loading = ref(false); // 按钮loading
const isCapslock = ref(false); // 是否大写锁定
const passwordVisible = ref(false); // 密码是否可见
const loginFormRef = ref(ElForm); // 登录表单ref
const disabled = ref(true);

const LogParams = reactive<LoginParams>({
    username: '',
    protoPassword: '',
    password:''
});

const loginRules = computed(() => {
    const prefix = appStore.language === 'en' ? 'Please enter ' : '请输入';
    return {
        username: [
            {
                required: true,
                trigger: 'blur',
                message: `${prefix}用户名`,
            },
        ],
        protoPassword: [
            {
                required: true,
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {
                    if (value.length < 6) {
                        callback(new Error('The password can not be less than 6 digits'));
                    } else {
                        callback();
                    }
                },
                message: `${prefix}密码`,
            },
        ],
    };
});

function checkCapslock (e: any) {
    const { key } = e;
    isCapslock.value = key && key.length === 1 && key >= 'A' && key <= 'Z';
}

function handleLogin () {
    loginFormRef.value.validate((valid: boolean) => {
        if (valid) {
            loading.value = true;
            //LogParams.password = CryptoJS.MD5(LogParams.protoPassword).toString()
            LogParams.password = LogParams.protoPassword
            userStore
                .login({
                    username: LogParams.username,
                    password: LogParams.password,
                })
                .then(() => {
                    //实现登录后重定向到用户原本想要访问的页面，同时保留页面相关的查询参数
                    const query: LocationQuery = route.query;
                    const redirect = (query.redirect as LocationQueryValue) ?? '/';
                    const otherQueryParams = Object.keys(query).reduce(
                        (acc: any, cur: string) => {
                            if (cur !== 'redirect') {
                                acc[cur] = query[cur];
                            }
                            return acc;
                        },
                        {}
                    );
                    router.push({ path: redirect, query: otherQueryParams });
                })
                .catch(() => {

                })
                .finally(() => {
                    loading.value = false;
                });
        }
    });
}

function onVerifySuccess () {
    console.log('onVerifySuccess')
    if(LogParams.username &&  LogParams.protoPassword){
        disabled.value = false
        handleLogin()
    }else{
        disabled.value = true
    }
}

function onVerifyFailed () {
    console.log('onVerifyFailed')
    disabled.value = true
}

onMounted(() => {
    // 主题初始化
    const theme = useSettingsStore().theme;
    useSettingsStore().changeSetting({ key: 'theme', value: theme });
    if (theme == 'dark') {
        document.documentElement.classList.add('dark');
    } else {
        document.documentElement.classList.remove('dark');
    }
});

</script>

<style lang="scss" scoped>
.login-container {
    .image{
        background: url('@/assets/images/login-left-bg.png') no-repeat center center;
        background-size: cover;
        padding:60px;
        color: #fff;
        p{
            font-size: 70px;
            font-family: 'DIN Web';
            font-weight: bold;
        }
        h1{
            font-size: 30px;
            font-weight: bold;
            margin-top: 20px;
        }
        img{
            width:80%;
        }
    }
    .form{
        padding:50px;
        background:url('@/assets/images/login-right-bg.png') no-repeat center top / cover;
        h2{
            font-size: 30px;
            &::before{
                content:'';
                width: 26px;
                height: 26px;
                margin-right: 10px;
                background: url('@/assets/images/login-title-bg.png') no-repeat center center;
            }
        }
    }

    .login-form {
        padding-top:20px;
        .input-item{
            margin-top: 20px;
            background-color: #f2f4f9;
            span{
                right:10px;
                top:50%;
                transform: translateY(-50%);
                line-height:1;
            }
            svg{
                color: #999999;
                &:hover{
                    color: var(--title-color);
                    transition: all .3s;
                }
            }
        }
    }
}

.el-form-item {
    border:1px solid #e3e6ee;
    background-color: #f2f4f9;
    border-radius: 5px;
}

:deep(.el-input) {
    height:40px;
    
    .el-input__wrapper {
        background:none;
        .el-form-item__content{
            line-height: normal;
        }
    }
}
</style>
